<?php

namespace app\user\controller;
use app\common\controller\UserBase;
use app\common\model\Sms;
use app\qcloud\model\Sms as Dx;
use app\common\model\Shop;

class Index extends UserBase
{
    protected $noLogin = ['login','register', 'captcha', 'captcha_sms'];
    protected $noAuth = ['index', 'account', 'uploadImage', 'uploadFile', 'uploadVideo', 'icon', 'logout'];

    protected function _initialize()
    {
        parent::_initialize();
        !config('website_status') && die(config('colse_explain'));
        $config = cache('db_config_data');
        if (!$config) {
            $config = [];
            foreach (model('config')->select() as $v) {
                $config[$v['group']][$v['name']] = $v['value'];
            }
            cache('db_config_data', $config);
        }
        config($config);
    }
    //会员中心
    public function index()
    {
        if (request()->isMobile()) {
            $shop = model('shop')->get(session('user_auth.shop_id'));
            $data['all_customer'] = model('customer')->count();
            $data['all_track'] = model('customerTrack')->count();
            $data['remind_no'] = model('customerRemind')->where(['status'=>'0'])->count();
            $data['all_order'] = model('customerOrder')->count();
            $user = model('user')->get(session('user_auth.user_id'));
            return $this->fetch('index_mobile',[
                'shop' => $shop,
                'data' => $data,
                'user' => $user,
            ]);
        }else{
            //return $this->fetch('index');
            $this->redirect('user/customer/index');
        }
    }
    //修改个人信息
    public function info()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['id'] = session('user_auth.user_id');
            $result = $this->validate($param, 'user');
            if ($result !== true) {
                $this->error($result);
            }
            $verify = input('_verify', true);
            if ($this->update('user', $param, $verify) === true) {
                insert_user_log('修改个人信息');
                // 保存状态
                $auth = [
                    'user_id' => session('user_auth.user_id'),
                    'shop_id' => session('user_auth.shop_id'),
                    'username' => session('user_auth.username'),
                    'realname' => $param['realname'],
                ];
                session('user_auth', $auth);
                session('user_auth_sign', data_auth_sign($auth));
                $this->success('修改成功', url('user/index/info'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch(is_Client('info'), [
            'data' => model('user')->with('userAuthGroupAccess')->where('id', session('user_auth.user_id'))->find(),
            'userAuthGroup' => model('userAuthGroup')->where('status', 1)->select(),]);
    }
    //账户类型
    public function account()
    {
        $user = model('user')->where('id',session('user_auth.user_id'))->find();
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['is_auth'] = '1';
            
            $param['admin_id'] = session('user_auth.user_id');
            //判断门店ID
            
            if($user['shop_id']=='0'){
                $param['create_time'] = time();
                $param['exp_time'] = time() + 2592000;
                if ($this->insert('shop', $param) === true) {
                    //修改账户信息
                    model('user')->where('id',session('user_auth.user_id'))->update(['shop_id'=>$this->insertId]);
                    insert_user_log('提交了账户认证资料');
                    // 保存状态
                    $auth = [
                        'user_id' => session('user_auth.user_id'),
                        'shop_id' => $this->insertId,
                        'username' => session('user_auth.username'),
                        'realname' => session('user_auth.realname'),
                    ];
                    session('user_auth', $auth);
                    session('user_auth_sign', data_auth_sign($auth));
                    session('user_admin','1');
                    $this->success('提交成功，等待审核', url('user/index/account'));
                } else {
                    $this->error($this->errorMsg);
                }
            }else{
                $param['update_time'] = time();
                if (model('shop')->where('id',$user['shop_id'])->update($param) === true) {
                    insert_user_log('修改账户认证资料');
                    $this->success('提交成功，等待审核', url('user/index/account'));
                } else {
                    $this->error($this->errorMsg);
                }
            }
        }else{
            $data = model('shop')->get($user['shop_id']);
        }
        return $this->fetch(is_Client('account'), [
            'data' => $data
            ]
        );
    }
    //子账户管理
    public function sub_user()
    {
        return $this->fetch(is_Client('sub_user'), ['list' => model('user')->where(['shop_id'=>session('user_auth.shop_id')])->order('id desc')->paginate(config('page_number'))]);
    }
    //子账户添加
    public function sub_user_add()
    {
        //检查工号数是否超标
        $yiyou = model('user')->where(['shop_id'=>session('user_auth.shop_id')])->count();
        $groupid = model('userAuthGroupAccess')->where('uid', session('user_auth.user_id'))->find();
        $taocan = model('userAuthGroup')->where('id', $groupid['group_id'])->find();
        if($yiyou >= $taocan['job_number']){
            $this->error('您的套餐只支持'.$taocan['job_number'].'个工号。请升级套餐');
        }
        $usergroup = model('userAuthGroupAccess')->where('uid',session('user_auth.user_id'))->find();
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['shop_id'] = session('user_auth.shop_id');
            $result = $this->validate($param, 'user');
            if ($result !== true) {
                $this->error($result);
            }
            //检查用户名是不是手机号码
            if(check_mobile($param['username']) == true){
                $this->error('用户名不能为手机号码');
            }
            empty($param['password']) && $this->error('密码不能为空');
            if ($this->insert('user', $param) === true) {
                model('userAuthGroupAccess')->save(['uid' => $this->insertId, 'group_id' => $usergroup['group_id']]);
                insert_user_log('添加了子账户');
                $this->success('添加成功', url('user/index/sub_user'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch(is_Client('sub_user_add'), ['userAuthGroup' => model('userAuthGroup')->where('status', 1)->select()]);
    }
    //子账户编辑
    public function sub_user_edit()
    {
        //检查工号数是否超标
        $yiyou = model('user')->where(['shop_id'=>session('user_auth.shop_id')])->count();
        $groupid = model('userAuthGroupAccess')->where('uid', session('user_auth.user_id'))->find();
        $taocan = model('userAuthGroup')->where('id', $groupid['group_id'])->find();
        if($yiyou >= $taocan['job_number']){
            $this->error('您的套餐只支持'.$taocan['job_number'].'个工号。请升级套餐');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $verify = input('_verify', true);
            if (empty($param['password'])) {
                unset($param['password']);
            }

            if ($this->update('user', $param, $verify) === true) {
                insert_user_log('修改了子账户');
                $this->success('修改成功', url('user/index/sub_user'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch(is_Client('sub_user_add'), [
            'data' => model('user')->with('userAuthGroupAccess')->where('id', input('id'))->find(),]);
    }
    //子账户删除
    public function sub_user_del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证账户是否主账户
            $shop = model('shop')->where(['id'=> session('user_auth.shop_id'),'admin_id'=>$param['id']])->find();
            if($shop){
                $this->error('主账户禁止删除');
            }
            if ($this->delete('user', $this->request->param()) === true) {
                model('userAuthGroupAccess')->where('uid', $param['id'])->delete();
                insert_user_log('删除了子账户');
                $this->success('删除成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
    }
    //登陆
    public function login()
    {
        is_user_login() && $this->redirect('user/index/index'); // 登录直接跳转
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (request()->isMobile()) {
                $result = $this->validate($param, 'login_mobile');
            }else{
                $result = $this->validate($param, 'login');
            }
            
            if ($result !== true) {
                $this->error($result);
            }
            //验证用户名是否手机号码
            if(check_mobile($param['username']) == true){
                $admin = model('user')->where(['mobile' => $param['username'],'password' => md5($param['password'])])->find();
            }else{
                $admin = model('user')->where(['username' => $param['username'],'password' => md5($param['password'])])->find();
            }
            if ($admin) {
                //检查是否到期
                if($admin['shop_id']!='0'){
                    $shop = model('shop')->get($admin['shop_id']);
                    if(strtotime($shop['exp_time']) < time()){
                        $this->error('您的软件服务已到期，请续费');
                    }else{
                        if($shop['admin_id']==$admin['id']){
                            session('user_admin','1');
                        }
                    }
                }
                $admin['status'] != 1 && $this->error('账号已禁用');
                // 保存状态
                $auth = [
                    'user_id' => $admin['id'],
                    'shop_id' => $admin['shop_id'],
                    'username' => $admin['username'],
                    'realname' => $admin['realname'],
                ];
                
                session('user_auth', $auth);
                session('user_auth_sign', data_auth_sign($auth));
                // 更新信息
                model('user')->save([
                    'last_login_time' => time(),
                    'last_login_ip'   => $this->request->ip(),
                    'login_count'     => $admin['login_count'] + 1,
                ], ['id' => $admin['id']]);
                insert_user_log('登录了后台系统');
                $this->success('登录成功', url('user/index/index'));
            } else {
                $this->error('账号或密码错误');
            }
        }
        return $this->fetch(is_Client('login'));
    }
    //注册
    public function register()
    {
        is_user_login() && $this->redirect('user/index/index'); // 登录直接跳转
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = $this->validate($param, 'register');
            if ($result !== true) {
                $this->error($result);
            }
            //验证用户名
            $users = \app\common\model\User::where(['username'=>$param['username']])->find();
            if($users){
                $this->error('用户名已存在');
            }
            //$code = Sms::where("mobile = '".$param['mobile']."' and code = '".$param['code']."' and end_time >='".time()."'")->order('id desc')->find();
            if ($this->insert('user', $param) === true) {
                model('userAuthGroupAccess')->save(['uid' => $this->insertId, 'group_id' => "1"]);
                //insert_user_log($param['username'].'注册了用户');
                $this->success('注册成功', url('user/index/index'));
            } else {
                $this->error($this->errorMsg);
            }
            
        }
        //$this->success('暂停注册');
        return $this->fetch('register');
    }
    //验证码
    public function captcha()
    {
        $config = [
            // 验证码字符集合
            'codeSet'  => '1234567890',
            // 验证码字体大小(px)
            'fontSize' => 16,
            // 是否画混淆曲线
            'useCurve' => false,
            // 验证码图片高度
            'imageH'   => 42,
            // 验证码图片宽度
            'imageW'   => 135,
            // 验证码位数
            'length'   => 4,
            // 验证成功后是否重置
            'reset'    => true,
        ];
        return captcha('', $config);
    }
    //验证码
    public function captcha_sms()
    {
        $mobile = input('mobile');
        //$sendsms = vendor('qcloudsms.sms');
        $sendsms = new Dx();
        //检查验证码是否已经达到5次
        $count = Sms::where(['mobile'=>$mobile])->count();
        if($count >= '5'){
            return ['status'=>0,'msg'=>'今日验证码次数已经达到5次，请明天再试'];
        }
        //检查验证码是否过期
        $count = Sms::where("mobile = '".$mobile."' and end_time >='".time()."'")->order('id desc')->find();
        if($count){
            //验证码未过期
            $sendsms->send($count['code'],$mobile);
            return ['status'=>1,'msg'=>'验证码已发送'];
        }else{
            //验证码已过期
            $data['code'] =  rand(100000,999999);
            $data['mobile'] = $mobile;
            $data['create_time'] = time();
            $data['end_time'] = time()+300;
            Sms::insert($data);
            $sendsms->send($data['code'],$data['mobile']);
            return ['status'=>1,'msg'=>'验证码已发送'];
        }
        //return json_decode(['status'=>$mobile]);
    }
    //上传图片
    public function uploadImage()
    {
        try {
            $file = $this->request->file('file');
            $qiniuConfig = include(__DIR__ ."/../../setting.php");
            //判断上传位置
            if($qiniuConfig['qiniu']['type']=='1'){//七牛
                //$file = $this->request->file('file');
                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                //$size = $this->sizecount(filesize($filePath));
                // 上传到七牛后保存的文件名
                $key = date('Y').'/'.date('md').'/'.date('YmdHis').rand(0,9999).substr(md5($file->getRealPath()),0,5). '.' . $ext;
                include APP_PATH . '/../vendor/qiniu/autoload.php';
                // 需要填写你的 Access Key 和 Secret Key
                $accessKey = $qiniuConfig['qiniu']['upak'];
                $secretKey = $qiniuConfig['qiniu']['upsk'];
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 要上传的空间
                $bucket = $qiniuConfig['qiniu']['upbucket'];
                $domain = $qiniuConfig['qiniu']['updomain'];
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return ["err"=>1,"msg"=>$err,"data"=>""];
                } else {
                    //返回图片的完整URL
                    return ['code' => 1, 'url' => $domain.$ret['key']];
                }
            }else{//默认本地
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'image');
                if ($info) {//               
                    $upload_image = unserialize(config('upload_image'));
                    if ($upload_image['is_thumb'] == 1 || $upload_image['is_water'] == 1 || $upload_image['is_text'] == 1) {
                        $object_image = \think\Image::open($info->getPathName());
                        // 图片压缩
                        if ($upload_image['is_thumb'] == 1) { 
                            $object_image->thumb($upload_image['max_width'], $upload_image['max_height']);
                        }
                        // 图片水印
                        if ($upload_image['is_water'] == 1) {
                            $object_image->water(ROOT_PATH . str_replace('/', '\\', trim($upload_image['water_source'], '/')), $upload_image['water_locate'], $upload_image['water_alpha']);
                        }
                        // 文本水印
                        if ($upload_image['is_text'] == 1) {
                            $font = !empty($upload_image['text_font']) ? str_replace('/', '\\', trim($upload_image['text_font'], '/')) : 'vendor\topthink\think-captcha\assets\zhttfs\1.ttf';
                            $object_image->text($upload_image['text'], ROOT_PATH . $font, $upload_image['text_size'], $upload_image['text_color'], $upload_image['text_locate'], $upload_image['text_offset'], $upload_image['text_angle']);
                        }
                        $object_image->save($info->getPathName());
                    }
                    return ['code' => 1, 'url' => '/uploads/image/' . str_replace('\\', '/', $info->getSaveName())];
                }else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    //上传文件
    public function uploadFile()
    {
        try {
            $file = $this->request->file('file');
            $qiniuConfig = include(__DIR__ ."/../../setting.php");
            //判断上传位置
            if($qiniuConfig['qiniu']['type']=='1'){//七牛
                //$file = $this->request->file('file');
                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                //$size = $this->sizecount(filesize($filePath));
                // 上传到七牛后保存的文件名
                $key = date('Y').'/'.date('md').'/'.date('YmdHis').rand(0,9999).substr(md5($file->getRealPath()),0,5). '.' . $ext;
                include APP_PATH . '/../vendor/qiniu/autoload.php';
                // 需要填写你的 Access Key 和 Secret Key
                $accessKey = $qiniuConfig['qiniu']['upak'];
                $secretKey = $qiniuConfig['qiniu']['upsk'];
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 要上传的空间
                $bucket = $qiniuConfig['qiniu']['upbucket'];
                $domain = $qiniuConfig['qiniu']['updomain'];
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return ["err"=>1,"msg"=>$err,"data"=>""];
                } else {
                    //返回图片的完整URL
                    return ['code' => 1, 'url' => $domain.$ret['key']];
                }
            }else{//默认本地
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'file');
                if ($info) {
                    return ['code' => 1, 'url' => '/uploads/file/' . str_replace('\\', '/', $info->getSaveName())];
                } else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    //上传视频
    public function uploadVideo()
    {
        try {
            $file = $this->request->file('file');
            $qiniuConfig = include(__DIR__ ."/../../setting.php");
            //判断上传位置
            if($qiniuConfig['qiniu']['type']=='1'){//七牛
                //$file = $this->request->file('file');
                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                //$size = $this->sizecount(filesize($filePath));
                // 上传到七牛后保存的文件名
                $key = date('Y').'/'.date('md').'/'.date('YmdHis').rand(0,9999).substr(md5($file->getRealPath()),0,5). '.' . $ext;
                include APP_PATH . '/../vendor/qiniu/autoload.php';
                // 需要填写你的 Access Key 和 Secret Key
                $accessKey = $qiniuConfig['qiniu']['upak'];
                $secretKey = $qiniuConfig['qiniu']['upsk'];
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 要上传的空间
                $bucket = $qiniuConfig['qiniu']['upbucket'];
                $domain = $qiniuConfig['qiniu']['updomain'];
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return ["err"=>1,"msg"=>$err,"data"=>""];
                } else {
                    //返回图片的完整URL
                    return ['code' => 1, 'url' => $domain.$ret['key']];
                }
            }else{//默认本地
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'video');
                if ($info) {
                    return ['code' => 1, 'url' => '/uploads/video/' . str_replace('\\', '/', $info->getSaveName())];
                } else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    //图标
    public function icon()
    {
        return $this->fetch();
    }
    //操作日志
    public function log()
    {
        return $this->fetch(is_Client('log'), ['list' => model('userLog')->where(['shop_id'=> session('user_auth.shop_id')])->order('create_time desc')->paginate(config('page_number'))]);
    }
    public function truncate()
    {
        if ($this->request->isPost()) {

            $param = model('userLog')->where(['shop_id'=> session('user_auth.shop_id')])->delete();

            $this->success('清空成功');

        }
    }
    // 修改密码
    public function editPassword()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 验证条件
            empty($param['password']) && $this->error('请输入旧密码');
            empty($param['new_password']) && $this->error('请输入新密码');
            empty($param['rep_password']) && $this->error('请输入确认密码');
            !check_password($param['new_password'], 6, 16) && $this->error('请输入6-16位的密码');
            $param['new_password'] != $param['rep_password'] && $this->error('两次密码不一致');
            $admin = model('user')->where('id', session('user_auth.user_id'))->find();
            $admin['password'] != md5($param['password']) && $this->error('旧密码错误');
            $data = ['id' => session('user_auth.user_id'), 'password' => $param['new_password']];
            if ($this->update('user', $data, false) === true) {
                insert_user_log('修改了登录密码');
                $this->success('更新成功', url('user/index/index'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch(is_Client('editPassword'));
    }

    // 退出登录
    public function logout()
    {
        insert_user_log('退出了后台系统');
        session('user_auth', null);
        session('user_auth_sign', null);
        session('user_admin', null);
        $this->redirect('user/index/login');
    }

    // 清除缓存
    public function clear()
    {
        clear_cache();
        insert_user_log('清除了系统缓存');
        $this->success('清除成功');
    }
    
    
    
    
}
